package bg.code.commons.builder.templte;

import bg.code.commons.builder.utils.FileUtil;
import bg.code.commons.builder.utils.Strings;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.StringTemplateResourceLoader;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;

/**
 * @author 郑兴泉 956607644@qq.com
 * @data 2020/3/18
 * 描述：
 */
public class BeetlTemplteEngine implements ITemplteEngine {


    static final StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
    static Configuration cfg;
    static GroupTemplate gt;

    static {
        try {
            cfg = Configuration.defaultConfiguration();
            cfg.setPlaceholderStart("#[");
            cfg.setPlaceholderEnd("]");
            cfg.setStatementStart("<##");
            cfg.setStatementEnd("##>");
            cfg.setHtmlTagSupport(false);
            cfg.setErrorHandlerClass("bg.code.commons.builder.templte.TemplateErrorHandler");
            gt = new GroupTemplate(resourceLoader, cfg);
            gt.registerFunctionPackage("sp", new Strings());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String render(String paramString, Map<String, Object> paramMap) throws Exception {
        Template template = gt.getTemplate(paramString);
        template.binding(paramMap);
        return template.render();
    }

    @Override
    public Path renderToFile(String paramString, Map<String, Object> paramMap, Path paramPath) throws Exception {
        Path directoryPath = paramPath.getParent();
        if (!directoryPath.toFile().exists()) {
            directoryPath.toFile().mkdirs();
        }
        // 写入文件
        FileUtil.strToFile(render(paramString, paramMap), paramPath.toFile());
        return directoryPath;
    }
}
